package it.koutifaris.travianmap.dal.sqlservices.travianserver;

import it.koutifaris.travianmap.dal.TravianServerService.TravianServer;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

import android.os.Parcel;
import android.os.Parcelable;

class TravianServerImpl implements TravianServer {

	private final String server;
	private URL mapUrl;
	private final Date lastUpdate;

	TravianServerImpl(String server, Date lastUpdate) {
		this.server = server;
		this.lastUpdate = lastUpdate;
	}

	@Override
	public URL getMapFileUrl() {
		if (mapUrl == null) {
			try {
				mapUrl = new URL("http://" + server + "/map.sql.gz");
			} catch (MalformedURLException e) {
				throw new RuntimeException(e);
			}
		}

		return mapUrl;
	}

	@Override
	public String getServerId() {
		return server;
	}

	@Override
	public Date getLastUpdate() {
		return lastUpdate;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((server == null) ? 0 : server.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof TravianServerImpl))
			return false;
		TravianServerImpl other = (TravianServerImpl) obj;
		if (server == null) {
			if (other.server != null)
				return false;
		} else if (!server.equals(other.server))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return getServerId();
	}

	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeString(server);
	}

	public final static Parcelable.Creator<TravianServerImpl> CREATOR = new Parcelable.Creator<TravianServerImpl>() {

		@Override
		public TravianServerImpl createFromParcel(Parcel source) {
			String server = source.readString();
			Date lastUpdate = null;
			long lastUpdateMillis = source.readLong();
			if (lastUpdateMillis > 0) {
				lastUpdate = new Date(lastUpdateMillis);
			}

			return new TravianServerImpl(server, lastUpdate);
		}

		@Override
		public TravianServerImpl[] newArray(int size) {
			return new TravianServerImpl[size];
		}
	};
}
